package com.example.server.controller;

import ch.qos.logback.core.util.FileUtil;
import com.example.server.entity.FilesSave;
import com.example.server.mapper.FileMapper;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.tomcat.util.http.fileupload.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

@RestController
@RequestMapping("/file")
public class FileController {
    @Autowired
    FileMapper fileMapper;
    @Value("${files.upload.path}") //    path: A:\Web\server\src\main\resources\files\  代表该文件夹下面
    private String fileUploadPath;

    @PostMapping("/upload")
    public String upload(@RequestParam("files") MultipartFile file) throws IOException {
        String fileName = file.getOriginalFilename();
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        long size = file.getSize();

        //生成文件名称通用方法
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
        Random r = new Random();
        StringBuilder tempName = new StringBuilder();
        tempName.append(sdf.format(new Date())).append(r.nextInt(100)).append(suffixName);
        String newFileName = tempName.toString();

        try {
            //保存文件
            byte[] bytes = file.getBytes();
            Path path = Paths.get(fileUploadPath + newFileName);
            Files.write(path, bytes);
        } catch (IOException e) {
            e.printStackTrace();
        }
        
        String url = "http://localhost:9090/file/" + newFileName;
        FilesSave save = new FilesSave();
        int i = 1;
        ++i;
        save.setId(i);
        save.setName(newFileName);
        save.setType(suffixName);
        save.setSize(size / 1024);
        save.setUrl(url);
        //save.setMd5(md5);
        fileMapper.save(save);
        return url;
    }

    @GetMapping("/{fileUUID}")
    public void download(@PathVariable String fileUUID, HttpServletResponse response) throws IOException {
        File uploadFile = new File(fileUploadPath,fileUUID);
        try (final ServletOutputStream outputStream = response.getOutputStream()){
            Files.copy(Paths.get(uploadFile.getPath()), outputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}